package org.freespace.api;

import cn.hutool.json.JSONUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Component
public class JmeterDriver {

    int jmeterClientPort = 15625;

    @Async
    public void start(Map<String, String> testData, String ip) {

        call(JMeterCmdHandler.JMETER_START + "##" + JSONUtil.toJsonStr(testData), ip, jmeterClientPort);
    }

    /**
     * 分布式调用压力机进行压力测试
     *
     * @param cmd  执行脚本命令
     * @param ip   压力机IP
     * @param port webSocket通信端口
     * @return
     */
    public void call(String cmd, String ip, int port) {
        log.info("cmd:{} ip:{} port:{}", cmd, ip, port);
        EventLoopGroup group = new NioEventLoopGroup();
        final JMeterCmdHandler jch = new JMeterCmdHandler(cmd);

        try {
            Bootstrap b = new Bootstrap();
            b.group(group);
            b.channel(NioSocketChannel.class);
            b.remoteAddress(new InetSocketAddress(ip, port));
            b.handler(new ChannelInitializer() {
                @Override
                protected void initChannel(Channel channel) throws Exception {
                    channel.pipeline().addLast(new ProtocolEncoder());
                    channel.pipeline().addLast(jch);
                }
            });

            ChannelFuture f = b.connect().sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
